package com.easidea.tim.service.system.permission;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springside.core.service.EntityService;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.easidea.tim.dao.system.permission.PermissionDao;
import com.easidea.tim.dao.system.permission.RoleDao;
import com.easidea.tim.entity.system.permission.Permission;
import com.easidea.tim.entity.system.permission.Role;
import com.easidea.tim.util.Page;

public class RoleService extends EntityService<Role, RoleDao> {

	private RoleDao roleDao;
	
	private PermissionDao permissionDao;
	
	/**
	 * 分页取角色列表
	 * @param name
	 * @param page
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page getRoleList(String name,Page page) {
		Criteria ca = this.getRoleListCriteria(name);
		ca.setProjection(Projections.count("id"));
		Integer totalNum = (Integer) ca.uniqueResult();
		Criteria ca1 = this.getRoleListCriteria(name);
		int startIndex = Page.getStartOfPage(page.getCurrentPageNo(), page.getPageSize());
		ca1.setFirstResult(startIndex);
		ca1.setMaxResults(page.getPageSize());
		List<Role> ls = (List<Role>) ca1.list();    
		Page resultPage = new Page(startIndex, totalNum, page.getPageSize(), ls);
		resultPage.setCurrentPageNo(page.getCurrentPageNo());

		return resultPage;
		
	}
	/**
	 * 查询条件
	 * @param name
	 * @return
	 */
	private Criteria getRoleListCriteria(String name) {
		Criteria ca = this.createUnDeletedCriteria();
		if (name != null && !name.equals("")) {
			ca.add(Restrictions.ilike("name", name, MatchMode.START));
		}
		
		return ca;
	}
	public boolean checkDelRole(long id) {
		return this.roleDao.checkDelRole(id); 
	}	
	/**
	 * 删除角色，更新deleted字段
	 * @param id
	 * @return
	 */
	public boolean deleteRole(long id) {
		Role role = this.get(id);
		try{
			role.setDeleted((short)1);
			role.setModifyTime(new Date());
			this.roleDao.getHibernateTemplate().update(role);
		}catch(DataAccessException de){
			de.printStackTrace();
			return false;
		}
		return true;
	}
	
	public String returnUrl() {
		String result="0";
		String flag = "0";
		Document document = load("d://change.xml");
		Node root = document.getDocumentElement();
		/** 如果root有子元素 */
		if (root.hasChildNodes()) {
			/** ftpnodes */
			NodeList ftpnodes = root.getChildNodes();
			/** 循环取得ftp所有节点 */
			for (int i = 0; i < ftpnodes.getLength(); i++) {
				NodeList ftplist = ftpnodes.item(i).getChildNodes();
				for (int k = 0; k < ftplist.getLength(); k++) {
					Node subnode = ftplist.item(k);
					if (subnode.getNodeName() == "change") {
						flag = subnode.getFirstChild().getNodeValue();
					}
					if(flag.equals("1")){
						if (subnode.getNodeName() == "url2") {
							result = subnode.getFirstChild().getNodeValue();
						}
					}
				}

			}
		}
		return result;
	}
	
	public static Document load(String filename) {
		Document document = null;
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse(new File(filename));
			document.normalize();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return document;
	}
	/**
	 * 获取所有权限
	 * @return
	 */
	public List<Permission> getAllPermissions(){
		return this.permissionDao.getAllValid();
	}
	/**
	 * 新增或修改保存角色
	 * @param role
	 * @return
	 */
	public boolean saveOrUpdate(Role role){
		try {
		if(role.getId() == -1) {
			this.roleDao.getHibernateTemplate().save(role);
		} else {
			this.roleDao.getHibernateTemplate().update(role);
		}
		}catch(DataAccessException de){
			de.printStackTrace();
			return false;
		}
		return true;
	}
	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}
	@Override
	public RoleDao getEntityDao() {
		// TODO Auto-generated method stub
		return roleDao;
	}
	public void setPermissionDao(PermissionDao permissionDao) {
		this.permissionDao = permissionDao;
	}
}
